<template>
	<div id="addAdderss">
		<div class="name">
			<span>收 货 人  </span>
			<input type="text" placeholder="请输入真实姓名" v-model="name" maxlength="20" />
			<img :style="showX==true?'display:inline-block;':'visibility:hidden;' " src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/change/close_b.png" style="width:.36rem;height:.36rem;" @click="rmname">
		</div>
		<div class="phone">
			<span>手机号码</span>
			<input type="tel" placeholder="请输入手机号码" onkeyup="value=value.replace( /^1[0-9]{10}$/)" v-model="phone">
			<img :style="showX==true?'display:inline-block;':'visibility:hidden;' " src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/change/close_b.png" style="width:.36rem;height:.36rem;" @click="rmphone">
		</div>
		<div class="cityAt">
			<div style="width: 15%;float: left;margin-left:.24rem;">
				<span>省市区</span>
			</div>
			<div style="width: 60%;line-height:1.1rem;height:1.1rem;float: left;" @click="addressChooose">
				<span class="gps">{{city}}</span>
			</div>
			<div @click="getAlladdress" style="overflow: hidden;width:15%;float:right;margin-right: .24rem;">
				<span class="where">定位</span>
				<img src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/location_a.png" />
			</div>
		</div>
		<div class="addressDetail">
			<span>详细地址</span>
			<input type="text" placeholder="请输入您的详细地址" v-model="addressDetail" maxlength="255" />
			<img :style="showX==true?'display:inline-block;':'visibility:hidden;' " src="https://khh-server.oss-cn-beijing.aliyuncs.com/resourse/IMG/static/change/close_b.png" style="width:.36rem;height:.36rem;" @click="rmaddressDetail">
		</div>
		<button class="send" @click="saveAddress()">保存</button>
		<div id="city" v-if="isshow" :style="{height:height + 'px'}">
			<div id="bottom">
				<header>
					<span class="cancle" @click="miss()">取消</span>
					<span class="city-choose">城市选择</span>
					<span class="back" @click="backto()">{{back}}</span>
				</header>
				<ul class="city scroll" v-if="showcity == 0">
					<li v-for="item in provincelist" @click="tocity(item.id,item.data,$event)">{{item.name}}</li>
				</ul>
				<ul v-else-if="showcity == 1">
					<li v-for="item in citylist" @click="toarea(item.id,item.data,$event)">{{item.name}}</li>
				</ul>
				<ul v-else>
					<li v-for="item in arealist" @click="area(item.id,item.data,$event)">{{item.name}}</li>
				</ul>
			</div>
		</div>
		<v-alert v-if="alertshow" :context="context"></v-alert>
	</div>
</template>

<script>
    import store from "../store/newStore.js";
	import Alert from "../alert.vue";
	import config from "../config/config.js";
	import share from "../share/share.js";
    import MtaH5 from 'mta-h5-analysis';
	export default{
		components:{
			"v-alert": Alert
		},
		data(){
			return{
				name:"",//收货人姓名
				phone:"",//收货人电话
				addressDetail:'',//详细地址
                address:[],
				provincelist:[],//省列表
				citylist:[],//市列表
				arealist:[],//区列表
				isshow:false,//选择地址弹窗是否显示
				height: document.body.offsetHeight,//屏幕高度
				showcity:[],//决定显示省市区的标志 0 显示省 1显示市 2显示区
				back:"",//地址栏头部右侧显示文字
				city1:[],//保存用户选择的省市区
				areaid:'',//区ID
				lng:'',//经度
				lat:'',//纬度
				addressid:'',//是否是修改地址标志
				alertshow: false,
				context:"",
				city:'',
				super_id:'',
                showX:true
			}
		},
        computed:{
            ticket(){
                return this.$store.state.getTicket;
            }
        },
		methods:{
			changeShow(){
				this.$parent.show = false;
			},
			yesdefault(){
				this.isdefault = false;
			},
			nodefault(){
				this.isdefault = true;
			},
			addressType(index){
				this.type = index;
			},
			miss(){
				this.isshow = false;
			},
			getAlladdress(){
			        var that=this;
                    wx.getLocation({
                        type : 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                        success : function(res) {
							var lnglatXY=[res.longitude, res.latitude];
                            axios.get('https://restapi.amap.com/v3/geocode/regeo',{
                               params:{
                                   output:'json',
                                   location:lnglatXY[0]+','+lnglatXY[1],
                                   key:'63826ceefa3fd1de6c8c7d72d4c9c12e',
                                   radius:1000,
                                   extensions:'all'
							   }
                            })
                                .then(function(result) {
									    that.city=result.data.regeocode.addressComponent.province+result.data.regeocode.addressComponent.city.join('')+result.data.regeocode.addressComponent.district;
                                        that.addressDetail=result.data.regeocode.formatted_address;
                                        that.areaid=result.data.regeocode.addressComponent.adcode;
                                }.bind(that))
                                .catch(function (error) {
                                    console.log(error);
                                });


                        },
                        cancel : function(res) {

                        }
                    });
			},
            addressChooose(){
                   this.isshow = true;
                   this.provincelist=this.address.data;
                   this.showcity=0;
			},
			tocity(id,list,$event){
			    for(var i in list){
                    this.$set(this.citylist,i,{"id":list[i]["id"],"name":list[i]["name"],"data":list[i]["data"]})
				}
			  this.showcity=1;
			  var el=$event.currentTarget.innerHTML;
			  this.city1[0]=el;
			},
            toarea(id,list,$event){
                    for(var i in list){
                        this.$set(this.arealist,i,{"id":list[i]["id"],"name":list[i]["name"]})
                    }
                this.showcity = 2;
                var el=$event.currentTarget.innerHTML;
                this.city1[1]=el;
            },
			area(id,list,$event){
                var el=$event.currentTarget.innerHTML;
                this.city1[2]=el;
                this.city=this.city1.join(' ');
                this.areaid=id;
                this.showcity = 0;
                this.isshow = false;
			},
			backto(){
				if(this.showcity == 0){
					return;
				}else if(this.showcity == 1){
                    var temp = this.showcity;
                    this.citylist=[];
                    temp--;
                    this.showcity = temp;
				} else{
					var temp = this.showcity;
					temp--;
					this.showcity = temp;
				}
			},
            rmname(){
			    this.name=''
			},
            rmphone(){
			    this.phone=''
			},
            rmaddressDetail(){
			  this.addressDetail=''
			},
			getAddressJson(){
                axios.get('https://wx.tianmaoetong.com/Public/static/address.json',{})
                    .then(function(response) {
                      this.address=response.data;
                    }.bind(this))
                    .catch(function (error) {
                        console.log(error);
                    });
			},
			saveAddress(){
			    var that=this;
                var reg=/^1[0-9]{10}$/;
			    if(this.$route.params.operate=='add'){
			        if(this.name==''||this.phone==''||this.addressDetail==''){
                            this.alertshow=true;
                            this.context='请完善收货信息';
                            setTimeout(function(){
                                that.alertshow=false;
							},2000)
					}else if(!reg.test(this.phone)){
                        this.alertshow=true;
                        this.context='请填写正确的手机号码';
                        setTimeout(function(){
                            that.alertshow=false;
                        },2000)
					}else{
                        var address_id=this.areaid,
                            re_name=this.name,
                            re_phone=this.phone,
                            re_address=this.addressDetail;
                        var value=JSON.stringify({"address_id":address_id,"re_name":re_name,"re_phone":re_phone,"re_address":re_address,"token":localStorage.getItem('token')}),
                            key=demo(value);
                        axios.post('/Home/Address/InsertAddress',{
                            value:value,
                            key:key,
                            ticket:this.ticket
                        },config)
                            .then(function(response) {
                                if(response.data.code==200){
                                    this.$store.commit('increment',response.data.ticket);
                                    this.$router.push('/address'+'/1')
                                }else {
                                    this.$store.commit('increment',response.data.ticket);
                                }
                            }.bind(this))
                            .catch(function (error) {
                                console.log(error);
                            });
					}

				}else if(this.$route.params.operate=='edit'){
			        if(this.name==''||this.phone==''||this.addressDetail==''){
                        this.alertshow=true;
                        this.context='请完善收货信息';
                        setTimeout(function(){
                            that.alertshow=false;
                        },2000)
					}else if(!reg.test(this.phone)){
                      this.alertshow=true;
                      this.context='请填写正确的手机号码';
                      setTimeout(function(){
                        that.alertshow=false;
                      },2000)
                    }else{
                        var address_id=this.areaid,
                            super_id=this.super_id,
                            re_name=this.name,
                            re_phone=this.phone,
                            re_address=this.addressDetail;
                        var value=JSON.stringify({"type":1,"super_id":super_id,"address_id":address_id,"re_name":re_name,"re_phone":re_phone,"re_address":re_address,"token":localStorage.getItem('token')}),
                            key=demo(value);
                        axios.post('/Home/Address/UpdateAddress',{
                            value:value,
                            key:key,
                            ticket:this.ticket
                        },config)
                            .then(function(response) {
                                if(response.data.code==200){
                                    this.$store.commit('increment',response.data.ticket);
                                    this.$router.push('/address'+'/1')
                                }else{
                                    this.$store.commit('increment',response.data.ticket);
                                    this.alertshow=true,
                                        this.context='修改失败';
                                    setTimeout(function(){
                                        that.alertshow=false;
                                    },2000)
                                }
                            }.bind(this))
                            .catch(function (error) {
                                console.log(error);
                            });
					}
				}else if(this.$route.params.operate=='detailAddress'){
			        if(this.name==''||this.phone==''||this.addressDetail==''){
                        this.alertshow=true;
                        this.context='请完善收货信息';
                        setTimeout(function(){
                            that.alertshow=false;
                        },2000)
					}else{
                        var address_id=this.areaid,
                            re_name=this.name,
                            re_phone=this.phone,
                            re_address=this.addressDetail;
                        var value=JSON.stringify({"address_id":address_id,"re_name":re_name,"re_phone":re_phone,"re_address":re_address,"token":localStorage.getItem('token')}),
                            key=demo(value);
                        axios.post('/Home/Address/InsertAddress',{
                            value:value,
                            key:key,
                            ticket:this.ticket
                        },config)
                            .then(function(response) {
                                if(response.data.code==200){
                                    this.$store.commit('increment',response.data.ticket);
                                    this.$router.back(-1)
                                }else {
                                    this.$store.commit('increment',response.data.ticket);
                                }
                            }.bind(this))
                            .catch(function (error) {
                                console.log(error);
                            });
					}

				}

			},

		},
		watch:{
			"showcity":function(){
				if(this.showcity == 0){
					this.back = "";
				}else{
					this.back = "上一级";
				}
			}
		},
		mounted(){

		},
		activated(){
			share({});
            MtaH5.init({
                "sid":'500594815',
                "cid":'500595819',
                "autoReport":0,
                "senseHash":0,
                "senseQuery":0,
                "performanceMonitor":0,
                "ignoreParams":[]
            });
            MtaH5.pgv();
            this.getAddressJson();
			if(this.$route.params.operate=='add'||this.$route.params.operate=='detailAddress'){
			    this.showX = false;
			}else{
                this.showX = true;
			};
            if(this.$route.params.operate=='edit'){
                this.name=this.$route.query.name;
                this.phone=this.$route.query.mobile;
                this.city=this.$route.query.address_info.value.join(' ');
                this.areaid=this.$route.query.address_info.id;
                this.addressDetail=this.$route.query.address;
                this.super_id=this.$route.query.id
            }
		},
		deactivated(){
            this.areaid='';
            this.name='';
            this.phone='';
            this.addressDetail='';
            this.city='';
		}
	}
</script>

<style>
</style>